import { isObject, isObjectLike, toString } from 'lodash'
import { Indicator, Toast, MessageBox } from 'mint-ui'

import config from '../config'
import bridge from '../bridge'

import { FILM_TYPE, ACTION_TYPE } from '../const'

const STORE_PREFIX = `ptys_${config.isDev ? 'dev' : 'pro'}_`

export default {
  data() {
    return {
      config,
      user: {},
      userId: ''
    }
  },

  mounted() {
    this.user = this.getStore('user') || {}
    this.userId = this.user ? this.user.userId : ''
  },

  computed: {},

  methods: {
    /**
     * title、url、desc、icon
     *
     * @param entry
     */
    setShareData(entry) {
      this.action('share', entry)
    },

    getImage(url) {
      if (!url.endsWith('webp') && url.indexOf('img.suhebar.com') === -1) {
        return url
      }
      return `https://images.weserv.nl/?url=${encodeURIComponent(url)}`
    },

    action(handler, params = '') {
      return new Promise(resolve => {
        let callback = null
        if (/share|setting|clearCache|getKeywordAdv/.test(handler)) {
          callback = data => resolve(JSON.parse(data))
        }

        // 所有参数采用字符串形式传递
        if (isObject(params)) {
          Object.keys(params).forEach(k => params[k] = isObjectLike(params[k]) ?
            params[k] : toString(params[k]))
        } else {
          params = toString(params)
        }
        bridge.then(b => {
          b.callHandler.apply(this, [handler, params, callback].filter(arg => arg !== undefined))
        })
      })
    },

    showLoading() {
      Indicator.open({
        spinnerType: 'fading-circle'
      })
    },

    hideLoading() {
      Indicator.close()
    },

    onLinkPage(path) {
      this.$router.push(path)
    },

    onItemDispatch(film, set, showVipDialog = true) {
      const {
        type, params, movieId, channel, data, title
      } = film

      if (+type === ACTION_TYPE.FILM || movieId) {
        if (config.env.isBrowser) {
          this.$router.push({
            name: 'film-detail',
            params: { id: params || movieId }
          })
        } else {
          if (!set) {
            if (channel && channel.key === FILM_TYPE.SERIES) { // 表示电视剧
              set = 1 // 默认第一集
            } else if (data && data.channel && data.channel.key === FILM_TYPE.SERIES) { // 表示电视剧
              set = 1
            }
          }

          this.action('filmDetail', {
            id: params || movieId,
            userId: this.userId,
            set
          })
        }
      } else if (+type === ACTION_TYPE.LINK || +type === ACTION_TYPE.DOWNLOAD) {
        if (this.config.env.isApp && params.startsWith('http')) {
          this.action('openVipBrowser', {
            name: 'VIP',
            url: params,
            showVipDialog
          })
        } else {
          location.href = params
        }
      } else if (+type === ACTION_TYPE.CHANNEL) {
        this.$router.push({
          path: '/film-list',
          query: { channel: params, title }
        })
      } else if (+type === ACTION_TYPE.HOME_CHANNEL) {
        this.$router.push({
          path: '/home',
          query: { id: params, title }
        })
      }
    },

    onBack() {
      if (this.config.env.isApp) {
        this.action('goback')
      } else {
        history.back()
      }
    },

    saveStore(key, val) {
      localStorage.setItem(STORE_PREFIX + key, JSON.stringify(val))
    },

    getStore(key) {
      return JSON.parse(localStorage.getItem(STORE_PREFIX + key))
    },

    clearStore(key) {
      localStorage.removeItem(STORE_PREFIX + key)
    },

    isMovie(data) {
      return data.channel.key === FILM_TYPE.MOVIE
    },

    $toast(msg) {
      Toast(msg)
    },

    $confirm(title, message, options) {
      return MessageBox.confirm(message, title, options)
    },

    checkLogin() {
      if (this.user.userId) {
        return true
      } else if (this.config.env.isApp) {
        this.action('login')
      } else {
        this.$router.push('/login')
      }
      return false
    },

    formatScore(score) {
      return Number(score).toFixed(1)
    }
  }
}
